﻿' Copyright (c) 2010 Skobkin.ru
' Permission is hereby granted, free of charge, to any person obtaining a copy of
'this software and associated documentation files (the "Software"), to deal in the
' Software without restriction, including without limitation the rights to use, copy,
' modify, merge, publish, distribute, sublicense, and/or sell copies of the Software,
' and to permit persons to whom the Software is furnished to do so, subject to the
' following conditions:
' The above copyright notice and this permission notice shall be included in all
' copies or substantial portions of the Software.
' THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
' INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
' PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
' HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
' OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
' SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

Imports System.Net
Imports System.IO
Imports System.Console
Module functions

    ' Функция сперта из Ras4PDA
    Function GetResponse(ByVal URL As String) As String
        ' Get HTML data
        ' http://www.vbdotnetheaven.com/UploadFile/mahesh/DownloadWebPage04252005073432AM/DownloadWebPage.aspx
        Dim HTMLCode = Nothing
        Dim request As WebRequest = WebRequest.Create(URL)
        Dim response As WebResponse
        Try
            response = request.GetResponse()
        Catch ex As Exception
            ' Страница не найдена
            Return "404"
        End Try

        Dim reader As StreamReader = New StreamReader(response.GetResponseStream())
        Dim str As String = reader.ReadToEnd()
        If str.IndexOf("Page Not Found") = -1 Then
            ' Возвращаем весь код.
            Return str
        Else
            ' Нифига не возвращаем.
            Return Nothing
        End If
    End Function

    Function ParseFriends(ByVal HTML As String) As String()
        ' Чистим все перед и все после
        HTML = HTML.Remove(1, HTML.IndexOf("</h2><p><a") + 10)
        HTML = HTML.Remove(HTML.IndexOf("</div>"), HTML.Length - HTML.IndexOf("</div>") - 1)

        ' Объявляем массив читателей и их количество
        Dim Readers() As String
        Dim Count As Long = 0

        ' Считаем читателей
        For i As Long = 0 To HTML.Length - 3
            If HTML.Substring(i, 3) = "</a" Then Count += 1
        Next

        ' Объявили массив с Count читателями
        ReDim Readers(Count)
        Count = 0 ' Теперь по нему будем считать

        Const NBegin As String = Chr(34) & Chr(47)
        Const NEnd As String = Chr(47) & Chr(34)

        For i As Long = 0 To HTML.Length - 2
            If HTML.Substring(i, 2) = NBegin Then ' "/
                ' Теперь ищем от позиции i до /"
                For j As Long = i + 2 To HTML.Length - 2
                    If HTML.Substring(j, 2) = NEnd Then ' /"
                        ' Присваиваем элементу #Count строчку между i и j
                        Readers(Count) = HTML.Substring(i + 2, j - i - 2)
                        ' Пишем в файл
                        Count += 1
                        ' Нашли - выходим!
                        Exit For
                    End If
                Next
            End If
        Next

        Return Readers
    End Function

    Function GetLast(ByVal FileName As String) As String()
        Dim Readers() As String
        Dim Count As Long = 0
        Dim SR As StreamReader = New StreamReader(FileName)

        ' Считаем строчки
        Do Until SR.EndOfStream
            SR.ReadLine()
            Count += 1
        Loop

        ' Закрываем\обнуляем
        SR.Close()
        ' Переобъявляем массив на нужное количество строк
        ReDim Readers(Count)
        ' Теперь Count - счетчик
        Count = 0
        ' Снова открываем файл
        SR = New StreamReader(FileName)
        Do Until SR.EndOfStream
            Readers(Count) = SR.ReadLine
            Count += 1
        Loop
        SR.Close()
        Return Readers
    End Function

    Sub Diff(ByVal NowSub As String(), ByVal FileName As String)
        ' Обрабатываем по строчке

        ' Суммарный текст Diff'а
        Dim SumText As String = Nothing

        Dim LastSub As String()
        ' Получаем прошлых подписчиков.
        LastSub = GetLast(FileName)

        ' Ищем тех кто подписался :)
        Dim Exist As Boolean
        For i As Long = 0 To NowSub.Length - 2
            Exist = False
            For j As Long = 0 To LastSub.Length - 2
                If NowSub(i).ToLower = LastSub(j).ToLower Then
                    ' Подписчик i из нового списка сохранился
                    Exist = True
                    Exit For
                End If
            Next
            If Not Exist Then
                ' Добавляем к выводу строчку
                SumText += "+" & NowSub(i) & vbCrLf
            End If
        Next

        ' Ищем гадов-отписчиков :-D
        For i As Long = 0 To LastSub.Length - 2
            Exist = False
            For j As Long = 0 To NowSub.Length - 2
                If LastSub(i).ToLower = NowSub(j).ToLower Then
                    Exist = True
                    Exit For
                End If
            Next
            If Not Exist Then
                SumText += "-" & LastSub(i) & vbCrLf
            End If
        Next

        ' Запись в лог
        If Logging And SumText <> Nothing Then
            LogAdd(Date.Now.ToString & " : " & vbCrLf & SumText, FileName & ".log")
        End If
        WriteLine(SumText)
    End Sub

    Sub LogAdd(ByVal Text As String, ByVal FileName As String)
        My.Computer.FileSystem.WriteAllText(FileName, Text, True)
    End Sub

End Module
